package com.echoesnet.echoesshortvideo.Activities;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.echoesnet.echoesshortvideo.Beans.FansFocusBean;
import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.CommonUtils;
import com.echoesnet.echoesshortvideo.Utils.SharePreUtils;
import com.echoesnet.echoesshortvideo.Utils.ToastUtils;
import com.echoesnet.echoesshortvideo.ViewModels.FansFocusViewModel;
import com.echoesnet.echoesshortvideo.views.adapters.FansFollowAdapter;
import com.echoesnet.echoesshortvideo.views.dialog.CustomAlertDialog;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.ui.emptyview.emptyViewOnShownListener;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class FanAndFocusAct extends BaseActivity
{
    private static final String TAG = FanAndFocusAct.class.getSimpleName();

    @BindView(R.id.urvList)
    UltimateRecyclerView urvList;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    private String type;
    private String tId;
    private FansFocusViewModel uViewModel;
    private List<FansFocusBean> mList;
    private FansFollowAdapter mListAdapter;
    private Unbinder unbinder;
    private static int START_USERINFOACTIVITY = 100;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fan_and_focus);
        unbinder = ButterKnife.bind(this);
        initView();
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        if (unbinder != null)
            unbinder.unbind();
    }

    private void initView()
    {
        mList = new ArrayList<>();
        type = getIntent().getStringExtra("type");
        tId = getIntent().getStringExtra("tId");

        mListAdapter = new FansFollowAdapter(this, mList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        urvList.setLayoutManager(linearLayoutManager);


        urvList.setHasFixedSize(false);
        urvList.reenableLoadmore();
        urvList.setLoadMoreView(R.layout.item_loadmore);
        urvList.setEmptyView(R.layout.common_empty_view, UltimateRecyclerView.EMPTY_CLEAR_ALL, new emptyViewOnShownListener()
        {
            @Override
            public void onEmptyViewShow(View mView)
            {
                String des = "";
                if (TextUtils.equals("follow", type))//关注
                {
                    des = "暂时还没有关注的人哦~";
                } else
                {
                    des = "暂时还没有粉丝哦~";
                }
                ((TextView) mView.findViewById(R.id.tvDesc)).setText(des);
                urvList.setBackgroundColor(getResources().getColor(R.color.transparent));
            }
        });
//        urvList.hideEmptyView();

        urvList.setAdapter(mListAdapter);

        urvList.setOnLoadMoreListener((itemsCount, maxLastVisiblePosition) -> {

//            if (maxLastVisiblePosition == mList.size()-1)
//            {
            chooseFanOrFollowMethodMore("loadMore");
            //    }

        });

        urvList.setDefaultOnRefreshListener(() -> {
            urvList.reenableLoadmore(); // 监听有关
            chooseFanOrFollowMethod("isRefresh");
        });

        mListAdapter.setOnItemLongClickListener(new FansFollowAdapter.ItemLongClickListener()
        {
            @Override
            public void onLongClick(View v, FansFocusBean bean, int position)
            {
                if (TextUtils.equals("follow", type) && TextUtils.equals(tId, SharePreUtils.getUId()))
                {
                    new CustomAlertDialog(FanAndFocusAct.this)
                            .builder()
                            .setCancelable(true)
                            .setBoldMsg("确认取消关注吗？")
                            .setMsg2Bold(true)
                            .setNegativeButton("确定", v1 ->
                            {
                                uViewModel.requestCancelFollowBean(bean, false);
                            })
                            .setPositiveTextColor(ContextCompat.getColor(FanAndFocusAct.this, R.color.C0321))
                            .setPositiveButton("取消", v2 ->
                            {
                            })
                            .setNegativeTextColor(ContextCompat.getColor(FanAndFocusAct.this, R.color.C0323p))
                            .show();
                }
            }
        });
        mListAdapter.setOnItemClickListener((view, infoEntity, position) -> {
            switch (view.getId())
            {
                case R.id.tvNickName:
                    break;
                case R.id.iv_icon:
                    //跳转个人详情
                    Intent intent = new Intent(this, CUserInfoAct.class);
                    intent.putExtra("uId", infoEntity.getUserId());
                    intent.putExtra("Activity", "Activity");
                    intent.putExtra("position", position);
                    // startActivity(intent);
                    startActivityForResult(intent, START_USERINFOACTIVITY);
                    break;
                case R.id.tv_focus:     //关注按钮
                    if (CommonUtils.checkUserStateFromActivity(FanAndFocusAct.this, null))
                    {
                        if (TextUtils.equals("0", infoEntity.getFollowOrNot()))
                        {
                            Logger.t(TAG).d("position>>" + position);
                            uViewModel.requestFollowBean(infoEntity.getUserId(), position);
                        }
                    }

                    break;
            }
        });
        uViewModel = ViewModelProviders.of(this).get(FansFocusViewModel.class);
        uViewModel.getFollowDetail().observe(this, new Observer<Map<String, Object>>()
        {
            @Override
            public void onChanged(@Nullable Map<String, Object> map)
            {
                //    更新UI
                urvList.setRefreshing(false);
                urvList.setBackgroundColor(getResources().getColor(R.color.C2E1A84));
                String isRefresh = (String) map.get("isRefresh");
                boolean hasMore = (boolean) map.get("hasMore");
                List<FansFocusBean> list = (List<FansFocusBean>) map.get("List");
                if (mList != null)
                {
                    if (TextUtils.equals("isRefresh", isRefresh))
                    {
                        mList.clear();

                    }

                    if(hasMore)
                    {

                    }else
                        {
                        urvList.disableLoadmore(); // 监听有关
                        mListAdapter.internalExecuteLoadingView();
                    }
                    // 添加去重复 ====
                    for (FansFocusBean fansBean : list)
                    {
                        if (mList.contains(fansBean))
                        {
                            int index = mList.indexOf(fansBean);
                            mList.remove(index);
                        }
                        mList.add(fansBean);
                    }
                    mListAdapter.notifyDataSetChanged();
                    if (mList.isEmpty())
                    {
                        urvList.showEmptyView();
                    } else
                    {
                        urvList.hideEmptyView();
                    }
                }
            }
        });

        uViewModel.getFocusListBack().observe(this, new Observer<Map<String, Object>>()
        {
            @Override
            public void onChanged(@Nullable Map<String, Object> map)
            {
                if (map != null)
                {
                    ToastUtils.showShort("关注成功");
                    int position = (int) map.get("position");
                    String status = (String) map.get("status");
                    mList.get(position).setFollowOrNot(status);
                    mListAdapter.notifyDataSetChanged();
                }
            }
        });

        uViewModel.getFanDetail().observe(this, new Observer<Map<String, Object>>()
        {
            @Override
            public void onChanged(@Nullable Map<String, Object> map)
            {
                urvList.setRefreshing(false);
                urvList.setBackgroundColor(getResources().getColor(R.color.C2E1A84));
                String isRefresh = (String) map.get("isRefresh");
                boolean hasMore = (boolean) map.get("hasMore");
                List<FansFocusBean> list = (List<FansFocusBean>) map.get("List");
                //更新UI
                urvList.setRefreshing(false);
                if (mList != null)
                {
                    if (TextUtils.equals("isRefresh", isRefresh))
                    {
                        mList.clear();
                    }

                    if(hasMore)
                    {

                    }else
                    {
                        urvList.disableLoadmore(); // 监听有关
                        mListAdapter.internalExecuteLoadingView();
                    }
                    // 添加去重复 ====
                    for (FansFocusBean fansBean : list)
                    {
                        if (mList.contains(fansBean))
                        {
                            int index = mList.indexOf(fansBean);
                            mList.remove(index);
                        }
                        mList.add(fansBean);
                    }
                    mListAdapter.notifyDataSetChanged();
                    if (mList.isEmpty())
                    {
                        urvList.showEmptyView();
                    } else
                    {
                        urvList.hideEmptyView();
                    }
                }
            }
        });

        uViewModel.getFollowBack().observe(this, new Observer<FansFocusBean>()
        {
            @Override
            public void onChanged(@Nullable FansFocusBean bean)
            {
                mList.remove(bean);
                if (mList.size() == 0)
                {
                    chooseFanOrFollowMethod("isRefresh");
                }
                mListAdapter.notifyDataSetChanged();

            }
        });


        chooseFanOrFollowMethod("loadMore");
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode)
        {
            case 100:
                Logger.t(TAG).d("data>>requestCode100:" + requestCode + ",resultCode:" + resultCode);
                if (data != null)
                {
                    String status = data.getStringExtra("focusStatus");
                    if (!TextUtils.isEmpty(status))
                    {
                        int position = data.getIntExtra("position", 0);
                        mList.get(position).setFollowOrNot(status);
                        mListAdapter.notifyDataSetChanged();
                    }
                }
                break;
            default:
                break;

        }
    }

    private void chooseFanOrFollowMethod(String isRefresh)
    {
        if (TextUtils.equals("fan", type))//粉丝
        {
            if (TextUtils.equals(SharePreUtils.getUId(), tId))
            {
                tvTitle.setText("我的粉丝");
                uViewModel.requestFansList("", isRefresh);//要查询的用户id(查看自己该字段为空)
            } else
            {
                tvTitle.setText("Ta的粉丝");
                uViewModel.requestFansList(tId, isRefresh);
            }
        } else if (TextUtils.equals("follow", type))//关注
        {
            if (TextUtils.equals(SharePreUtils.getUId(), tId))
            {
                tvTitle.setText("我的关注");
                uViewModel.requestFollowList("", isRefresh);//要查询的用户id(查看自己该字段为空)
            } else
            {
                tvTitle.setText("Ta的关注");
                uViewModel.requestFollowList(tId, isRefresh);
            }
        }
    }

    private void chooseFanOrFollowMethodMore(String isRefresh)
    {
        if (TextUtils.equals("follow", type))//关注
        {
            if (TextUtils.equals(SharePreUtils.getUId(), tId))
            {
                tvTitle.setText("我的关注");
                uViewModel.requestFollowMoreList("", isRefresh);//要查询的用户id(查看自己该字段为空)
            } else
            {
                tvTitle.setText("Ta的关注");
                uViewModel.requestFollowMoreList(tId, isRefresh);
            }
        } else if (TextUtils.equals("fan", type))//粉丝
        {
            if (TextUtils.equals(SharePreUtils.getUId(), tId))
            {
                tvTitle.setText("我的粉丝");
                uViewModel.requestFansMoreList("", isRefresh);//要查询的用户id(查看自己该字段为空)
            } else
            {
                tvTitle.setText("Ta的粉丝");
                uViewModel.requestFansMoreList(tId, isRefresh);
            }
        }
    }

    @OnClick(R.id.iv_back)
    public void onClick()
    {
        finish();
    }
}
